﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using DX.Views;
using DX.ViewModels;

namespace DX
{
    public partial class ViewControl : UserControl, IView, IAttach, IDetach
    {
        public ViewControl()
        {
            ViewModelBindingSource = new BindingSource();
            DataContext = ViewModelBindingSource;
            InitializeComponent();

        }
        /// <summary>
        /// 
        /// </summary>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1104:Fields should not have public accessibility", Justification = "<挂起>")]
        public BindingSource ViewModelBindingSource;
        /// <summary>
        /// 
        /// </summary>
        [Category("MVVM")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Browsable(false)]
        public IViewModel ViewModel
        {
            get
            {
                return ViewModelBindingSource?.DataSource as IViewModel;
            }

            protected set
            {
                if (value == null) return;

                ViewModelBindingSource.DataSource = value;
            }
        }




        protected virtual void OnAttachView(IView view, IViewModel viewModel)
        {
            this.ViewModel = viewModel;
        }

        protected virtual void OnDetachView(IView view, IViewModel viewModel)
        {
            this.ViewModel = null;
        }
        void IAttach.Attach(IView view, IViewModel viewModel)
        {
            OnAttachView(view, viewModel);
        }

        void IDetach.Detach(IView view, IViewModel viewModel)
        {
            OnDetachView(view, viewModel);
        }
    }
}
